package hidalgo.expenses.activity;

import hidalgo.expenses.R;
import hidalgo.expenses.SessionManager;
import hidalgo.expenses.dao.NoteDao;
import hidalgo.expenses.entities.Note;
import hidalgo.expenses.utils.Constants;
import hidalgo.expenses.utils.HideAnimation;
import hidalgo.expenses.utils.Properties;
import hidalgo.expenses.widgets.ActionBar;
import hidalgo.expenses.widgets.LinedEditText;
import hidalgo.expenses.widgets.popupmenu.ActionItem;
import hidalgo.expenses.widgets.popupmenu.QuickAction;

import java.util.Calendar;

import android.content.ComponentName;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

public class NoteEditor extends BaseActivity {

	// action id
	private static final int ID_CANCEL = 1;
	private static final int ID_SAVE = 2;

	private LinedEditText letxtText;
	private ActionBar actionBar;
	private QuickAction subMenu;

	private int noteId = 0;
	private boolean isEditMode = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.note_editor_activity);

		setUpActionBar();
		setUpActionBarSubMenu();

		letxtText = (LinedEditText) findViewById(R.id.letxtNote);

		Bundle extras = this.getIntent().getExtras();

		if (extras != null) {
			isEditMode = extras.getBoolean(Constants.NOTE_EDITOR_ISEDITMODE);
			if (isEditMode) {
				noteId = extras.getInt("NOTEID");
			}
		}

		if (isEditMode) {

			fillNote(noteId);

		}
	}

	private void fillNote(int noteId) {

		new AsyncTask<Integer, Integer, Note>() {

			protected void onPreExecute() {

				actionBar.showProgressBar();
				actionBar.getProgressBar().startLoading(
						Properties.progressBarSpeed);
			};

			@Override
			protected Note doInBackground(Integer... params) {

				int noteId = params[0];

				return NoteDao.getNotesById(noteId);
			}

			protected void onPostExecute(Note note) {

				if (note != null) {

					letxtText.setText(note.getText());

				} else {
					Toast.makeText(NoteEditor.this, "Error al cargar Nota",
							Toast.LENGTH_SHORT).show();
				}

				actionBar.getProgressBar().completeLoading();
				actionBar.getProgressBar().startAnimation(
						new HideAnimation(1.0f, 1.0f, 1.0f, 0.0f, 500,
								actionBar.getProgressBar(), true));

			};
		}.execute(noteId);

	}

	private void setUpActionBarSubMenu() {
		ActionItem nextItem = new ActionItem(ID_SAVE, "Guardar", getResources()
				.getDrawable(R.drawable.menu_down_arrow));
		ActionItem prevItem = new ActionItem(ID_CANCEL, "Cancelar",
				getResources().getDrawable(R.drawable.menu_up_arrow));

		// use setSticky(true) to disable QuickAction dialog being dismissed
		// after an item is clicked
		prevItem.setSticky(false);
		nextItem.setSticky(false);

		// create QuickAction. Use QuickAction.VERTICAL or
		// QuickAction.HORIZONTAL parameter to define layout orientation
		subMenu = new QuickAction(this, QuickAction.VERTICAL);

		subMenu.addActionItem(nextItem);
		subMenu.addActionItem(prevItem);

		subMenu.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
			public void onItemClick(QuickAction source, int pos, int actionId) {
				ActionItem actionItem = subMenu.getActionItem(pos);

				if (actionId == ID_SAVE) {
					Toast.makeText(getApplicationContext(), "Guardando nota",
							Toast.LENGTH_SHORT).show();

					Note note = new Note(noteId, Calendar.getInstance()
							.getTime(), letxtText.getText().toString(),
							SessionManager.userId);
					if (isEditMode) {
						updateNote(note);
					} else {
						addNote(note);
					}
				} else if (actionId == ID_CANCEL) {
					Toast.makeText(getApplicationContext(), "Cancelando",
							Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(getApplicationContext(),
							actionItem.getTitle() + " selected",
							Toast.LENGTH_SHORT).show();
				}
			}

		});

		subMenu.setOnDismissListener(new QuickAction.OnDismissListener() {
			public void onDismiss() {
				Toast.makeText(getApplicationContext(), "Dismissed",
						Toast.LENGTH_SHORT).show();
			}
		});

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		subMenu.dismiss();
	}

	private void addNote(Note note) {
		new AsyncTask<Note, Void, Boolean>() {

			@Override
			protected Boolean doInBackground(Note... params) {

				boolean success = false;
				Note note = params[0];

				success = NoteDao.insert(note);

				return success;
			}

			protected void onPostExecute(Boolean success) {

				if (success) {
					Toast.makeText(NoteEditor.this, "Nota creada",
							Toast.LENGTH_SHORT).show();

					NoteEditor.this.finish();
				} else {
					Toast.makeText(NoteEditor.this, "Error al crear Nota",
							Toast.LENGTH_SHORT).show();
				}

			};

		}.execute(note);
	}

	private void updateNote(final Note note) {
		new AsyncTask<Note, Void, Boolean>() {

			@Override
			protected Boolean doInBackground(Note... params) {

				boolean success = false;
				Note note = params[0];

				success = NoteDao.update(note);

				return success;
			}

			protected void onPostExecute(Boolean success) {

				if (success) {
					Toast.makeText(NoteEditor.this, "Nota Actualizada",
							Toast.LENGTH_SHORT).show();

					// send result data
					Intent i = new Intent();
					i.putExtra(Constants.NOTE_EDITOR_ISEDITMODE, isEditMode);
					i.putExtra(Constants.NOTE_OBJECT, note);
					setResult(RESULT_OK, i);

					NoteEditor.this.finish();
				} else {
					Toast.makeText(NoteEditor.this, "Error al Actualizar Nota",
							Toast.LENGTH_SHORT).show();
				}

			};

		}.execute(note);
	}

	private void setUpActionBar() {

		actionBar = (ActionBar) findViewById(R.id.actionBar);
		actionBar.setTitle("Editor de Notas");
		// set home icon that does nothing when the user clicks on it
		actionBar.setHomeLogo(R.drawable.ic_title_home_default,
				new OnClickListener() {
					public void onClick(View v) {
						NoteEditor.this.finish();
					}
				});
		// sets an action icon that displays a Toast upon clicking
		actionBar.addActionIcon(R.drawable.info_64, new OnClickListener() {
			public void onClick(View v) {
				subMenu.show(v);
				subMenu.setAnimStyle(QuickAction.ANIM_REFLECT);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate menu from XML resource
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.editor_options_menu, menu);

		// Append to the
		// menu items for any other activities that can do stuff with it
		// as well. This does a query on the system for any activities that
		// implement the ALTERNATIVE_ACTION for our data, adding a menu item
		// for each one that is found.
		Intent intent = new Intent(null, getIntent().getData());
		intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
		menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0,
				new ComponentName(this, NoteEditor.class), null, intent, 0,
				null);

		return super.onCreateOptionsMenu(menu);
	}

	public int getNoteId() {
		return noteId;
	}

	public void setNoteId(int noteId) {
		this.noteId = noteId;
	}

}
